﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        private Graphics graphics;
        public Form1()
        {
            InitializeComponent();
            graphics = this.CreateGraphics();
        }
        double per1=0;
        double per2=0;
        double th1 = 0;
        double th2 = 0;
        int n = 0;
        double leng = 0;
        Color penColor = Color.Green;
        private void button1_Click(object sender, EventArgs e)
        {
            if (graphics == null) graphics = this.CreateGraphics();

            // 从控件中读取参数值
            n = (int)numericUpDownDepth.Value;
            leng = (double)numericUpDownLength.Value;
            per1 = (double)numericUpDownRightLengthRatio.Value;
            per2 = (double)numericUpDownLeftLengthRatio.Value;
            th1 = (double)numericUpDownRightAngle.Value * Math.PI / 180;
            th2 = (double)numericUpDownLeftAngle.Value * Math.PI / 180;
            
            drawCayleyTree(n, 200, 310, leng, -Math.PI / 2, penColor);
        }       

        void drawCayleyTree(int n, double x0, double y0, double leng, double th, Color penColor)
        {
            if (n == 0) return;
            double x1 = x0 + leng * Math.Cos(th);
            double y1 = y0 + leng * Math.Sin(th);

            drawLine(x0, y0, x1, y1, penColor);
            drawCayleyTree(n - 1, x1, y1, per1 * leng, th + th1, penColor);
            drawCayleyTree(n - 1, x1, y1, per2 * leng, th - th2, penColor);
        }

        void drawLine(double x0, double y0, double x1, double y1, Color penColor)

        {
            try
            {
                graphics.DrawLine(
                new Pen(penColor),
                (int)x0, (int)y0, (int)x1, (int)y1);
            }
            catch (Exception)
            {
                Console.WriteLine("invalid input,try again");
            }
                    
        }

        private void button2_Click(object sender, EventArgs e)
        {
            colorDialogPenColor1.ShowDialog();
            penColor = colorDialogPenColor1.Color;
        }
    }
}